import { getMyAIAgents, searchAgents, getAgentDetailById } from '@/utils/api'
import { type AIAgent } from './interface'
import { aiAgentStore } from '../stores/ai-agent'
import { createAndEnsureAIAgent } from './lib'
import { defaultAgentId, defaultAgentName } from './config'

class AIAgentMgr {
  private static instance: AIAgentMgr | null = null

  modes: AIAgent[] = [] as AIAgent[]

  defaultAgent: AIAgent = {
    id: defaultAgentId,
    key: defaultAgentId,
    type: defaultAgentId,
    name: defaultAgentName
  }

  // 私有构造函数防止外部实例化
  private constructor() {
    console.log('AIAgentMgr instance created.')
  }

  // 静态方法用于获取单例实例
  public static getInstance(): AIAgentMgr {
    if (!AIAgentMgr.instance) {
      AIAgentMgr.instance = new AIAgentMgr()
    }
    return AIAgentMgr.instance
  }

  // 示例方法
  public setup(): void {
    console.log('Called setup.')
  }

  public async getMyAIAgents(): Promise<Array<AIAgent>> {
    try {
      const data = await getMyAIAgents()
      this.modes = data.map((item: {}) => {
        const model: AIAgent = createAndEnsureAIAgent(item)
        return model
      })

      const agentStore = aiAgentStore()
      agentStore.setMyAgents(this.modes)

      return this.modes
    } catch (error) {
      console.error('Error fetching models:', error)
      return Promise.reject(error)
    }
  }

  public isDefaultAgent(agent: AIAgent) {
    if (
      agent?.type?.toLowerCase() === defaultAgentId.toLowerCase() ||
      agent?.id?.toLowerCase() === defaultAgentId.toLowerCase()
    ) {
      return true
    }

    return false
  }

  public async getAgentDetailById(agentId: string): Promise<AIAgent> {
    try {
      const data = await getAgentDetailById(agentId)
      const agent = createAndEnsureAIAgent(data)
      return agent
    } catch (error) {
      console.error('Error getAgentDetailById:', error)
      return Promise.reject(error)
    }
  }

  public async searchAgents(
    pageIndx?: number,
    pageSize?: number,
    name?: string
  ): Promise<Array<AIAgent>> {
    try {
      const data = await searchAgents(pageIndx, pageSize, name)
      this.modes = data.list.map((item: {}) => {
        return createAndEnsureAIAgent(item)
      })
      return this.modes
    } catch (error) {
      console.error('Error search agents:', error)
      return Promise.reject(error)
    }
  }
}

const agentMgr = AIAgentMgr.getInstance()
export default agentMgr
